package com.ruoyi.web.controller.api.webapp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.house.domain.IndexBanner;
import com.ruoyi.house.service.IIndexBannerService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;


/**
 * Baidu map api Controller
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@RestController
@RequestMapping("/api/webapp/house/baiduMap")
public class WAppBaiduMapApiController extends BaseController {

    @Value("${baiduMap.ak}")
    private String ak;

    /**
     * 根据ip获取当前城市
     */
    @Anonymous
    @GetMapping("/getCity")
    public AjaxResult getCity(HttpServletRequest request) {

        String ipAddr = IpUtils.getIpAddr(request);

//        String ip = "182.139.116.181"; // 需要替换成要查询的IP地址
        String cityName = this.getLocationCity(ipAddr);
        if (StringUtils.isNotNull(cityName)) {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("cityName", cityName);
            return ajax;
        }
        return AjaxResult.error(HttpStatus.GET_CITY_FAIL,"定位获取城市失败");
    }

    private String getLocationCity(String ip) {

        try {
//            String ak = "LB3tfoRl9qw23PHpIoQQabmFsGM39EEK"; // 需要替换成你的百度地图访问密钥

            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(String.format("https://api.map.baidu.com/location/ip?ip=%s&ak=%s", ip, ak));
            CloseableHttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                StringBuilder stringBuilder = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }

//                JSONObject jsonObject = new JSONObject(stringBuilder.toString());
//                String city = jsonObject.getJSONObject("content").getString("address_detail").getString("city");

                JSONObject jsonObject = JSON.parseObject(stringBuilder.toString());
                if (jsonObject.getInteger("status") == 0) {
                    String city = jsonObject.getJSONObject("content").getJSONObject("address_detail").getString("city");
                    System.out.println("城市：" + city);
                    return city.replace("市", "");
                } else {
                    return null;
                }
            }

            response.close();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}